<script setup lang="ts">
import { ref, onMounted, computed, watch, h, nextTick } from 'vue';
import lotteryService from '../../utils/p5/p5Service';
// 导入ECharts
import * as echarts from 'echarts';
// 导入Ant Design Vue组件
import { Button, Table, Pagination, Card, message, Spin } from 'ant-design-vue';

// 数字格式化辅助函数
const formatNumber = (num: number | undefined): string => {
  if (num === undefined || isNaN(num)) {
    return '--';
  }
  return num.toLocaleString('zh-CN');
};

// 定义数据类型
interface LotteryData {
  issueNumber: string;
  date: string;
  numbers: number[];
  sales?: number;
  directBet: {
    count?: number;
    prize?: number;
  };
  bonusNumber?: number;
}

// 定义响应式数据
// 控制顶部表格是否倒序排列的开关
const sortTableDescending = ref(false);

// 控制是否启用排列三功能（只显示前三位）
const usePermutationThree = ref(false);

// 监听排列三状态变化，更新分析结果
watch(usePermutationThree, () => {
  updateAnalysisResults();
});

// 更新分析结果
function updateAnalysisResults() {
  if (lotteryData.value.length === 0) return;

  try {
    loading.value = true;
    analysisResult.value = lotteryService.analyzeLotteryData(lotteryData.value, usePermutationThree.value);
    positionAnalysisResult.value = lotteryService.analyzeNumbersByPosition(lotteryData.value, usePermutationThree.value);
    mostFrequentCombinations.value = lotteryService.findMostFrequentCombinations(lotteryData.value, 5, usePermutationThree.value);
    highProbabilityCombinations.value = lotteryService.generateHighProbabilityCombinations(lotteryData.value, 5, usePermutationThree.value);
    renderECharts(); // 重新渲染图表
  } catch (err) {
    error.value = '更新分析结果失败';
    console.error(err);
  } finally {
    loading.value = false;
  }
}

// 重新生成高几率组合
function regenerateHighProbabilityCombinations() {
  try {
    loading.value = true;
    highProbabilityCombinations.value = lotteryService.generateHighProbabilityCombinations(lotteryData.value, 5, usePermutationThree.value);
    message.success('成功生成新的高几率组合');
  } catch (err) {
    error.value = '生成高几率组合失败';
    console.error(err);
  } finally {
    loading.value = false;
  }
}
const lotteryData = ref<LotteryData[]>([]);
const analysisResult = ref<{ [key: string]: number }>({});
const positionAnalysisResult = ref<{ [key: string]: { [key: string]: number } }>({});
// 历史出现频率最高的组合
const mostFrequentCombinations = ref<number[][]>([]);
// 预测的高几率组合
const highProbabilityCombinations = ref<number[][]>([]);
const loading = ref(true);
const error = ref('');
const currentPage = ref(1);
const itemsPerPage = ref(10);
const usePagination = ref(false);

// 计算所有可能的数字
const getAllNumbers = computed(() => {
  const numbers = new Set<string>();
  for (const position in positionAnalysisResult.value) {
    for (const number in positionAnalysisResult.value[position]) {
      numbers.add(number);
    }
  }
  // 排序数字
  return Array.from(numbers).sort((a, b) => parseInt(a) - parseInt(b));
});

// 定义位置分析表格列
const positionAnalysisColumns = computed(() => {
  const columns = [
    {
      title: '位置',
      dataIndex: 'position',
      key: 'position',
    }
  ];
  // 为每个数字添加一列
  getAllNumbers.value.forEach(number => {
    columns.push({
      title: number,
      dataIndex: `number_${number}`,
      key: `number_${number}`,
    });
  });
  return columns;
});

// 计算位置分析表格数据
const positionanalysisTableData = computed(() => {
  const data = [];
  for (const position in positionAnalysisResult.value) {
    const row: any = {
      position: `第${position}位`,
      key: position,
    };
    // 为每个数字设置出现次数
    getAllNumbers.value.forEach(number => {
      row[`number_${number}`] = positionAnalysisResult.value[position][number] || 0;
    });
    data.push(row);
  }
  return data;
});

// 定义表格列
const columns = [
  {
    title: '期号',
    dataIndex: 'issueNumber',
    key: 'issueNumber',
  },
  {
    title: '开奖日期',
    dataIndex: 'date',
    key: 'date',
  },
  {
    title: usePermutationThree.value ? '排列三号码' : '开奖号码',
    dataIndex: 'numbers',
    key: 'numbers',
    customRender: ({ text }) => (
      h('div', { style: 'display: flex; gap: 8px;' },
        text.slice(0, usePermutationThree.value ? 3 : text.length).map((num: number, index: number) => (
          h('span', {
            key: index,
            style: 'width: 24px; height: 24px; border-radius: 50%; background: #f5222d; color: white; display: flex; align-items: center; justify-content: center; font-size: 14px;'
          }, num)
        ))
      )
    ),
  },
  {
    title: '总销售额（元）',
    dataIndex: 'sales',
    key: 'sales',
    customRender: ({ text }) => formatNumber(text),
  },
  {
    title: '注数',
    key: 'directBet.count',
    customRender: ({ record }) => formatNumber(record.directBet?.count),
  },
];

// 搜索相关
const searchQuery = ref('');
const matchStartOnly = ref(false); // 控制是否只匹配开头
const filteredData = computed(() => {
  if (!searchQuery.value) return lotteryData.value;

  // 去掉搜索 query 中的空格和逗号
  const cleanQuery = searchQuery.value.replace(/[ ,]/g, '');

  return lotteryData.value.filter(item => {
    // 检查号码是否包含搜索的数字
    const numbersStr = item.numbers.join('');
    if (matchStartOnly.value) {
      // 只匹配开头且顺序对的
      return numbersStr.startsWith(cleanQuery);
    } else {
      // 普通包含匹配
      return numbersStr.includes(cleanQuery);
    }
  });
});

// 搜索结果数量计算属性
const searchResultCount = computed(() => filteredData.value.length);

// 计算出现最多的5个数字
const top5Numbers = computed(() => {
  // 转换为数组并按出现次数排序
  const sortedNumbers = Object.entries(analysisResult.value)
    .sort((a, b) => b[1] - a[1])
    .slice(0, 5); // 取前5个

  return sortedNumbers.map(([number, count]) => ({
    number,
    count
  }));
});

// 定义出现最多的数字表格列
const topNumbersColumns = [
  {
    title: '排名',
    dataIndex: 'rank',
    key: 'rank',
  },
  {
    title: '数字',
    dataIndex: 'number',
    key: 'number',
  },
  {
    title: '出现次数',
    dataIndex: 'count',
    key: 'count',
  }
];

// 计算出现最多的数字表格数据
const topNumbersTableData = computed(() => {
  return top5Numbers.value.map((item, index) => ({
    ...item,
    rank: index + 1,
    key: index
  }));
});

// 定义组合表格列
const combinationColumns = [
  {
    title: '排名',
    dataIndex: 'rank',
    key: 'rank',
  },
  {
    title: '数字组合',
    dataIndex: 'combination',
    key: 'combination',
    customRender: ({ text }) => text.join(', '),
  },
  {
    title: '出现次数',
    dataIndex: 'count',
    key: 'count',
  }
];

// 控制是否倒序排列的开关
const sortDescending = ref(false);

// 定义表格组件配置，处理dragHandle插槽
const tableComponents = {
  header: {
    cell: {
      render: (props: any) => {
        const { children, column } = props;

        // 将 children 转换为数组
        const childrenArray = children ? (Array.isArray(children) ? children : [children]) : [];

        return h('div', { className: 'ant-table-cell' }, [
          column && column.dragHandle ? h('span', { className: 'ant-table-drag-icon' }, [
            h('svg', { xmlns: 'http://www.w3.org/2000/svg', width: '16', height: '16', viewBox: '0 0 16 16', fill: 'none' }, [
              h('circle', { cx: '8', cy: '4', r: '1', fill: '#9CA3AF' }),
              h('circle', { cx: '8', cy: '8', r: '1', fill: '#9CA3AF' }),
              h('circle', { cx: '8', cy: '12', r: '1', fill: '#9CA3AF' })
            ])
          ]) : null,
          ...childrenArray // 使用处理后的数组
        ]);
      }
    }
  }
};


// 计算组合表格数据
const combinationTableData = computed(() => {
  // 从lotteryData中统计组合出现次数
  const combinationCounts = {};
  lotteryData.value.forEach(item => {
    const combinationStr = item.numbers.join('');
    if (combinationCounts[combinationStr]) {
      combinationCounts[combinationStr]++;
    } else {
      combinationCounts[combinationStr] = 1;
    }
  });

  // 基础数据处理
  let data = mostFrequentCombinations.value.map((combination, index) => ({
    combination,
    rank: index + 1,
    count: combinationCounts[combination.join('')] || 0, // 使用实际统计的组合出现次数
    key: index
  }));

  // 根据开关状态决定是否倒序
  if (sortDescending.value) {
    data = data.reverse().map((item, index) => ({
      ...item,
      rank: index + 1,
      key: index
    }));
  }

  return data;
});

// 计算分页后的数据
const paginatedData = computed(() => {
  let data = filteredData.value;

  // 根据开关状态决定是否倒序
  if (sortTableDescending.value) {
    data = [...data].reverse();
  }

  if (!usePagination.value) return data;

  const startIndex = (currentPage.value - 1) * itemsPerPage.value;
  const endIndex = startIndex + itemsPerPage.value;
  return data.slice(startIndex, endIndex);
});

// 计算总页数
const totalPages = computed(() => {
  if (!usePagination.value) return 1;
  return Math.ceil(filteredData.value.length / itemsPerPage.value);
});

// 切换分页功能
function togglePagination() {
  usePagination.value = !usePagination.value;
  currentPage.value = 1; // 重置到第一页
}

// 加载数据
onMounted(async () => {
  try {
    loading.value = true;
    const data = await lotteryService.fetchLotteryData();
    lotteryData.value = data;
    updateAnalysisResults(); // 使用新函数更新分析结果
    message.success('数据加载成功');
  } catch (err) {
    error.value = '加载彩票数据失败';
    console.error(err);
  } finally {
    loading.value = false;
  }
});

// 渲染ECharts图表
function renderECharts() {
  // 增加延迟确保DOM完全渲染
  nextTick(() => {
    const chartDom = document.getElementById('echartsContainer') as HTMLDivElement;
    if (chartDom) {
      console.log('找到ECharts容器');
      // 确保analysisResult有数据
      if (Object.keys(analysisResult.value).length > 0) {
        const myChart = echarts.init(chartDom);

        const option = {
          title: {
            text: usePermutationThree.value ? '排列三号码出现频率分析' : '号码出现频率分析',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: Object.keys(analysisResult.value),
            axisLabel: {
              interval: 0
            }
          },
          yAxis: {
            type: 'value',
            min: 0
          },
          series: [{
            name: '出现次数',
            type: 'bar',
            data: Object.values(analysisResult.value),
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                offset: 0,
                color: 'rgba(54, 162, 235, 1)'
              }, {
                offset: 1,
                color: 'rgba(54, 162, 235, 0.2)'
              }])
            },
            emphasis: {
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                  offset: 0,
                  color: 'rgba(30, 144, 255, 1)'
                }, {
                  offset: 1,
                  color: 'rgba(30, 144, 255, 0.2)'
                }])
              }
            },
            barWidth: '60%',
            animationDelay: (idx) => idx * 10
          }],
          animationEasing: 'elasticOut',
          animationDelayUpdate: (idx) => idx * 5
        };

        myChart.setOption(option);

        // 响应式调整
        window.addEventListener('resize', () => {
          myChart.resize();
        });
      } else {
        console.error('analysisResult没有数据');
      }
    } else {
      console.error('未找到ECharts容器元素');
      // 打印当前DOM结构，用于调试
      console.log('当前DOM结构:', document.body.innerHTML);
    }
  });
}
</script>

<template>
  <div class="lottery-analyzer">
    <Card title="排列五数据分析" style="margin-bottom: 20px;">
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
        <div style="display: flex; gap: 10px;">
          <Button type="primary" @click="togglePagination">
            {{ usePagination ? '关闭分页' : '开启分页' }}
          </Button>
          <Button :type="sortTableDescending ? 'primary' : 'default'"
            @click="sortTableDescending = !sortTableDescending">
            {{ sortTableDescending ? '已开启倒序' : '开启倒序' }}
          </Button>
          <Button :type="usePermutationThree ? 'primary' : 'default'"
            @click="usePermutationThree = !usePermutationThree">
            {{ usePermutationThree ? '已开启排列三' : '开启排列三' }}
          </Button>
        </div>
        <div style="display: flex; align-items: center;">
          <span style="margin-right: 10px; font-weight: bold;">搜索结果: {{ searchResultCount }}</span>
          <input type="text" v-model="searchQuery" placeholder="搜索中奖号码..."
            style="padding: 6px 12px; border: 1px solid #d9d9d9; border-radius: 4px; margin-right: 10px;" />
          <Button :type="matchStartOnly ? 'primary' : 'default'" @click="matchStartOnly = !matchStartOnly">
            {{ matchStartOnly ? '已开启开头匹配' : '开启开头匹配' }}
          </Button>
        </div>
      </div>

      <!-- 加载状态 -->
      <Spin v-if="loading">
        <template #default>
          <div>加载中...</div>
        </template>
      </Spin>

      <!-- 错误信息 -->
      <div v-else-if="error">
        {{ message.error(error) }}
      </div>

      <!-- 数据表格 -->
      <div v-else-if="lotteryData.length > 0">
        <Table :data-source="paginatedData" :columns="columns" style="margin-bottom: 20px;" />

        <!-- 分页控制 -->
        <Pagination v-if="usePagination" v-model:current-page="currentPage" :page-size="itemsPerPage"
          :total="lotteryData.length" show-total style="margin-top: 20px; text-align: center;" />

        <!-- 预测结果 -->
        <Card title="高几率组合预测" style="margin-top: 30px;">
          <Button type="primary" @click="regenerateHighProbabilityCombinations" style="margin-bottom: 20px;">
            重新生成高几率组合
          </Button>
          <div class="prediction-result">
            <div class="high-probability-combinations">
              <h3>其他高几率组合:</h3>
              <div v-for="(combination, index) in highProbabilityCombinations" :key="index" class="combination-item">
                <span class="combination-index">{{ index + 1 }}.</span>
                <span v-for="(num, numIndex) in combination" :key="numIndex" class="number-item">{{ num }}</span>
              </div>
            </div>
          </div>
        </Card>

        <!-- 分析结果 -->
        <Card title="号码出现频率分析" style="margin-top: 30px;">
          <div style="width: 100%;">
            <p style="text-align: center; margin-bottom: 10px;">ECharts 图表</p>
            <div id="echartsContainer" style="width: 100%; height: 400px;"></div>
          </div>

          <div class="frequency-list">
            <div v-for="(count, number) in analysisResult" :key="number" class="frequency-item">
              号码 {{ number }}: 出现 {{ count }} 次
            </div>
          </div>
        </Card>

        <!-- 位置分析结果 -->
        <Card title="各位数字出现频率分析" style="margin-top: 30px;">
          <Table :columns="positionAnalysisColumns" :data-source="positionanalysisTableData" bordered
            style="margin-top: 20px;" />
        </Card>

        <!-- 出现最多的5个数字组合 -->
        <Card title="出现频率最高的5组数字组合" style="margin-top: 30px;">
          <div style="display: flex; justify-content: flex-end; margin-bottom: 10px;">
            <Button :type="sortDescending ? 'primary' : 'default'" @click="sortDescending = !sortDescending">
              {{ sortDescending ? '已开启倒序' : '开启倒序' }}
            </Button>
          </div>
          <Table :columns="combinationColumns" :data-source="combinationTableData" bordered style="margin-top: 20px;"
            :components="tableComponents" />
        </Card>


      </div>

      <!-- 无数据状态 -->
      <div v-else class="no-data">
        暂无彩票数据
      </div>
    </Card>
  </div>
</template>

<style scoped>
.lottery-analyzer {
  max-width: 1200px; margin: 0 auto; padding: 20px;
}

.frequency-list {
  display: flex; flex-wrap: wrap; gap: 10px; margin-top: 20px;
}

.frequency-item {
  background-color: #f0f2f5; padding: 8px 16px; border-radius: 4px;
}

.position-charts-container {
  display: flex; flex-wrap: wrap; gap: 20px; justify-content: center;
}

.position-chart-item {
  flex: 1 1 400px; min-width: 300px; max-width: 100%;
}

.prediction-result {
  padding: 10px;
}

.predicted-combination {
  margin-bottom: 20px;
}

.combination-numbers {
  display: flex; gap: 10px; margin-top: 10px;
}

.number-item {
  display: inline-block; width: 36px; height: 36px; line-height: 36px; text-align: center; background-color: #1890ff; color: white; border-radius: 50%; font-weight: bold;
}

.high-probability-combinations {
  margin-top: 20px;
}

.combination-item {
  display: flex; align-items: center; margin-bottom: 10px;
}

.combination-index {
  margin-right: 10px; font-weight: bold;
}
</style>